package com.woniu.day8.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.day8.pojo.UserInfo;
import com.woniu.day8.pojo.dto.UserInfoDto;
import com.woniu.day8.pojo.vo.UserInfoVo;
import com.woniu.day8.service.Impl.UserInfoServiceImpl;
import com.woniu.day8.service.UserInfoService;
import com.woniu.day8.util.JWTUtil;
import com.woniu.day8.util.RedisUtils;
import com.woniu.day8.util.ResultMessage;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class LoginController {
    private static final String REDIS_CODE_PREFIX = "lbw666";
    @Autowired
    private RedisUtils redis;
    @Autowired
    private UserInfoServiceImpl userInfoService;
    /**
     * 随机生成一个验证码 的图片
     */
    @RequestMapping("getCode")
    public ResultMessage<Map> getCode( String codeId){
        //判断用户是否是第一次访问？生成新的codeId:直接使用
        if(codeId==null||codeId.isEmpty()){
            //生成唯一的key(用糊涂包依赖工具)
            codeId = IdUtil.getSnowflakeNextIdStr();
        }
        //设置验证码图片长、宽、验证码字符数、干扰线宽度
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 30, 4, 10);
        //设置字体样式和大小
        lineCaptcha.setFont(new Font("仿宋", Font.BOLD, 30));
        //获取验证码
        String code = lineCaptcha.getCode().toUpperCase();//转换大写
        //保存验证码到redis中
        redis.set(REDIS_CODE_PREFIX+codeId,code,60);
        System.out.println("验证码:" + code);
        //转为Base64字符串
        String imageBase64 = lineCaptcha.getImageBase64Data();
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put("img",imageBase64);
        reqMap.put("codeId",codeId);
        return ResultMessage.success(reqMap);
    }

    /**
     * 登陆接口
     * @param userInfoDto
     * @param response
     * @return
     */
    @RequestMapping("/login")
    public ResultMessage login(@RequestBody UserInfoDto userInfoDto, HttpServletResponse response) {
        // 判断验证码是否正确
        String CODE = redis.get(REDIS_CODE_PREFIX + userInfoDto.getCodeId());
        if (userInfoDto.getCodeId() == null || userInfoDto.getCodeId().isEmpty()) {
            return ResultMessage.fail("验证码不存在", 522, userInfoDto);
        }

        if (CODE == null) {
            return ResultMessage.fail("验证码已过期", 523, userInfoDto);
        }

        if (!CODE.equalsIgnoreCase(userInfoDto.getVerifyCode().toUpperCase())) {
            return ResultMessage.fail("验证码错误", 521, userInfoDto);
        }

        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoDto, userInfo);
        ResultMessage userMessage = userInfoService.login(userInfo);
        // 检查返回结果是否是UserInfo对象
        if (userMessage.getCode() ==200) {
            UserInfo user = (UserInfo) userMessage.getData();
            System.out.println(user);
            if (user != null) {
                UserInfoVo resultUser = new UserInfoVo();
                //使用sa-token
                BeanUtils.copyProperties(user,resultUser);//拷贝用户信息
                StpUtil.logout(user.getId());//删除旧token
                StpUtil.login(user.getId(),30*60);
                SaTokenInfo tokenInfo = StpUtil.getTokenInfo();//获取token
                resultUser.setTokenInfo(tokenInfo);
                Map<String,Object> reqMap = new HashMap<>();
                reqMap.put("token",resultUser.getTokenInfo().getTokenValue());
                reqMap.put("user",user);
                return ResultMessage.success(reqMap);
            } else {
                return userMessage;
            }
        } else {
            return userMessage;
        }
    }
    /**
     * 注册接口
     */
    @PostMapping("/register")
    public ResultMessage register(@RequestBody UserInfoDto userInfoDto) {

        // 检查用户名是否已存在
        QueryWrapper<UserInfo> checkWrapper = new QueryWrapper<>();
        checkWrapper.eq("username", userInfoDto.getUsername());
        UserInfo existingUser = userInfoService.getOne(checkWrapper);

        if (existingUser != null) {
            return ResultMessage.fail("用户名已存在", 530, userInfoDto);
        }

        // 创建新用户
        UserInfo newUser = new UserInfo();
        BeanUtils.copyProperties(userInfoDto, newUser);

        // 对密码进行加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(userInfoDto.getPassword().getBytes());
        newUser.setPassword(encryptedPassword);

        // 设置默认头像（可选）
        if (newUser.getImgpath() == null || newUser.getImgpath().isEmpty()) {
            newUser.setImgpath("/default-avatar.png");
        }

        // 保存用户
        boolean saved = userInfoService.save(newUser);

        if (saved) {
            // 注册成功后可选自动登录
            UserInfo resUserInfo = new UserInfo();
            resUserInfo.setUsername(newUser.getUsername());
            resUserInfo.setImgpath(newUser.getImgpath());
            return ResultMessage.success("注册成功",200 ,resUserInfo);
        } else {
            return ResultMessage.fail("注册失败，请稍后重试", 531, userInfoDto);
        }
    }

}
